package com.partner.action.common;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.partner.bean.member.Member;
import com.partner.bean.order.Order;
import com.partner.bean.order.Ordermi;
import com.partner.bean.withdraw.Withdraw;
import com.partner.frame.BaseAction;
import com.partner.frame.common.CommonInstans;
import com.partner.frame.util.ExcelUtils;
import com.partner.frame.util.MemberUtil;
import com.partner.service.member.MemberService;
import com.partner.service.order.OrderService;
import com.partner.service.order.OrdermiService;
import com.partner.service.sysright.SysManagerService;
import com.partner.service.withdraw.WithdrawService;

@RestController
public class InOutPutExcelAction extends BaseAction {

	@Autowired
	private OrderService orderService;
	@Autowired
	MemberService memberService;
	@Autowired
	private OrdermiService ordermiService;
	@Autowired
	private SysManagerService sysManagerService;
	@Autowired
	private WithdrawService withdrawService;
	/**
     * 进入导入页面
     * @throws Exception
     */
	@RequestMapping(value = "/member/inExcelImportPage")
    public ModelAndView inExcelImportPage(HttpServletRequest request) throws Exception {

		ModelAndView mv = new ModelAndView();
        mv.setViewName("/pages/member/importexcel");
		
		return mv;

    }
	/**
     * 读取excel更新数据
     *
     * @param upfile
     * @param	
     * @param
     * @throws Exception
     */
	@PostMapping(value = "/member/importExcel")
    public Map<String, String> importExcel(MultipartFile upfile,HttpServletRequest request) throws Exception {

        HashMap<String, String> map = new HashMap<>();
        InputStream in = upfile.getInputStream();
        //读取excel中的内容
        List<Member> lineDownOrders = ExcelUtils.getBankListByExcel(in);
        for(int i=0;i < lineDownOrders.size() ; i++){
        	Member member = lineDownOrders.get(i);
        	Member newmember = new Member();
        	int sysuserid = (int)request.getSession().getAttribute(CommonInstans.LOGINUSERID);
        	newmember.setSysuserid(sysuserid);
        	newmember.setName(member.getName());
        	newmember.setSex(member.getSex());
        	newmember.setTel(member.getTel());
    			if(member.getNum()!=null && member.getNum()!=0){
    				Member m = memberService.selectByNum(member.getNum());
    				if(m!=null){
    					newmember.setPname(m.getName());
    					newmember.setPtel(m.getTel());
    					newmember.setPid(m.getId());
    				}
    			}
    			newmember.setStatus(1);
    			newmember.setDisabled(0);
    			newmember.setSonnum(0);
    			newmember.setLevel(1);
    			newmember.setMembernum(0);
    			newmember.setSaleamount(0);
    			newmember.setWithdrawintegral(0);
    			newmember.setNum(MemberUtil.getMaxNum(memberService)+1);
    			Member ismember = new Member();
    			ismember.setTel(member.getTel());
    			List<Member> isexsitmember = memberService.selectAll(ismember);
    			if(isexsitmember.size()==0){
    				Integer id = memberService.insert(newmember);
    				MemberUtil.addAccountOrder(id,memberService,ordermiService,sysManagerService);
    			}
        }
        map.put("status", lineDownOrders.size()+"");
        return map;

    }
	
	/**
     * 导出财务数据报表
     * @return
     */
    @RequestMapping(value = "/final/export")
    @ResponseBody
    public void export(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取数据
    	Withdraw withdraw = new Withdraw();
    	List<Withdraw> list = withdrawService.selectAll(withdraw);

        //excel标题
        String[] title = {"序号","姓名","手机号","提现积分","提现渠道","姓名","账号","银行支行名称","税点","税费","支付金额","审核状态","申请时间"};

        //excel文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
        String fileName = "财务管理"+sdf.format(new Date())+".xls";

        //sheet名
        String sheetName = "财务管理";
        
        String[][] content = new String[list.size()][title.length]; 
        
        for (int i = 0; i < list.size(); i++) {
            //content[i] = new String[title.length];
        	Withdraw obj = list.get(i);
            content[i][0] = (i + 1) +"" ;
            if(obj.getNickname()!=null)
            content[i][1] = obj.getNickname();
            content[i][2] = obj.getTel();
            if(obj.getWithdrawintegral()!=null)
            content[i][3] = obj.getWithdrawintegral().toString();
            String qdmc = "" ; //（1：微信  2：支付宝  3：银行卡）
            if(obj.getWithdrawchannel()!=null){
            	int qd = obj.getWithdrawchannel() ; 
            	if(qd==1){
            		qdmc = "微信";
            	}else if(qd==2){
            		qdmc = "支付宝";
            	}else{
            		qdmc = "银行卡";
            	}
            }
            content[i][4] = qdmc;
            content[i][5] = obj.getName() ;
            content[i][6] = obj.getAccount();
            content[i][7] = obj.getBank();
            if(obj.getTaxpoint()!=null)
            content[i][8] = obj.getTaxpoint().toString();
            if(obj.getTaxation()!=null)
            content[i][9] = obj.getTaxation().toString();
            if(obj.getPayamount()!=null)
            content[i][10] = obj.getPayamount().toString() ;
            String statusmc = "" ; //0：申请中 1：审核成功  2：审核被拒  3:兑付  4：拒绝兑付'
            if(obj.getWithdrawchannel()!=null){
            	int qd = obj.getStatus() ; 
            	if(qd==1){
            		statusmc = "审核成功";
            	}else if(qd==2){
            		statusmc = "审核被拒";
            	}else if(qd==3){
            		statusmc = "已兑付";
            	}else if(qd==4){
            		statusmc = "拒绝兑付";
            	}else{
            		statusmc = "申请中" ;
            	}
            }
            content[i][11] = statusmc;
            if(obj.getCreatetime()!=null){
            	Date createtime = obj.getCreatetime();
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                content[i][12] = sdf1.format(createtime);
            }
            
        }

        //创建HSSFWorkbook 
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
        	this.setResponseHeader(response, fileName);
        	OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
        }catch(Exception e){
        	e.getStackTrace();
        }
        
   }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 账单提现/收入报表导出
     * @return
     */
    @PostMapping(value = "/export/reportbill")
    @ResponseBody
    public void reportbill(HttpServletRequest request,HttpServletResponse response,Order order) throws Exception {
    	
    	Integer order1 = orderService.report1(order);//收入总和
		Withdraw w1 = new Withdraw();
		w1.setStarttime(order.getStarttime());
		w1.setEndtime(order.getEndtime());
		Integer withdrar = withdrawService.report1(w1);//提现总和
		//excel标题
        String[] title = {"序号","项目","积分"};
      //excel文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
        String fileName = "账单报表"+sdf.format(new Date())+".xls";

        //sheet名
        String sheetName = "账单报表";
        
        String[][] content = new String[2][title.length];
        
        content[0][0] = "1" ;
        content[0][1] = "收入";
        content[0][2] = order1 + "";
        content[1][0] = "2" ;
        content[1][1] = "提现";
        content[1][2] = withdrar + "";
        
        //创建HSSFWorkbook 
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
        	this.setResponseHeader(response, fileName);
        	OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
        }catch(Exception e){
        	e.getStackTrace();
        }
    }
    /**
     * 收入来源报表导出
     * @return
     */
    @PostMapping(value = "/export/reportsource")
    @ResponseBody
    public void reportsource(HttpServletRequest request,HttpServletResponse response,Ordermi order) throws Exception {
    	
    	List<Ordermi> list = ordermiService.report2(order);//收入总和
    	//excel标题
        String[] title = {"序号","收入来源","积分"};

        //excel文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
        String fileName = "收入来源报表"+sdf.format(new Date())+".xls";

        //sheet名
        String sheetName = "收入来源报表";
        
        String[][] content = new String[list.size()][title.length]; 
        
        for (int i = 0; i < list.size(); i++) {
        	Ordermi od = list.get(i);
        	 content[i][0] = (i + 1) +"" ;
             if(od.getProductname()==null){
             content[i][1] = "天使父母";
             }else{
                 content[i][1] = od.getProductname();
             }
             if(od.getSettleaccounts()!=null)
             content[i][2] = od.getSettleaccounts().toString();
        }
        
      //创建HSSFWorkbook 
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
        	this.setResponseHeader(response, fileName);
        	OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
        }catch(Exception e){
        	e.getStackTrace();
        }
    	
    }
    /**
     * 支出来源报表导出
     * @return
     */
    @PostMapping(value = "/export/reportpay")
    @ResponseBody
    public void reportpay(HttpServletRequest request,HttpServletResponse response,Order order) throws Exception {
    	
    	List<Order> list = orderService.report3(order);//收入总和
    	//excel标题
        String[] title = {"序号","来源","积分"};

        //excel文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
        String fileName = "来源报表"+sdf.format(new Date())+".xls";

        //sheet名
        String sheetName = "来源报表";
        
        String[][] content = new String[list.size()][title.length]; 
        
        for (int i = 0; i < list.size(); i++) {
        	Order od = list.get(i);
        	 content[i][0] = (i + 1) +"" ;
             if(od.getSource()!=null){
            	 if(od.getType()!=null&&od.getType()==1){
            		 content[i][1] = "一级推广";
            	 }else if(od.getType()!=null&&od.getType()==2){
            		 content[i][1] = "二级推广";
            	 }else if(od.getType()!=null&&od.getType()==3){
            		 content[i][1] = "一级销售";
            	 }else if(od.getType()!=null&&od.getType()==4){
            		 content[i][1] = "二级销售";
            	 }else if(od.getType()!=null&&od.getType()==5){
            		 content[i][1] = "分红";
            	 }
             }
             
             if(od.getSumscore()!=null)
             content[i][2] = od.getSumscore().toString();
        }
        
      //创建HSSFWorkbook 
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
        	this.setResponseHeader(response, fileName);
        	OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
        }catch(Exception e){
        	e.getStackTrace();
        }
    }
    /**
     * 区域报表导出
     * @return
     */
    @PostMapping(value = "/export/reportarea")
    @ResponseBody
    public void reportarea(HttpServletRequest request,HttpServletResponse response,Ordermi ordermi) throws Exception {
    	
    	List<Ordermi> list = ordermiService.report4(ordermi);//拥有开户权限的管理员的开户人数
		for(int i=0; i<list.size(); i++){
			Integer sysuserid = list.get(i).getSysuserid();
			Integer totalamount = ordermiService.getTotalAmountByUserId(sysuserid);
			list.get(i).setSettleaccounts(totalamount);
		}
		//excel标题
        String[] title = {"序号","姓名","电话","开户人数","销售总积分"};

        //excel文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");
        String fileName = "区域报表"+sdf.format(new Date())+".xls";

        //sheet名
        String sheetName = "区域报表";
        
        String[][] content = new String[list.size()][title.length]; 
        
        for (int i = 0; i < list.size(); i++) {
        	Ordermi od = list.get(i);
        	 content[i][0] = (i + 1) +"" ;
             if(od.getName()!=null)
            	 content[i][1] = od.getName();
             if(od.getTel()!=null)
            	 content[i][2] = od.getTel().toString();
             if(od.getNum()!=null)
                 content[i][3] = od.getNum().toString();
             if(od.getSettleaccounts()!=null)
                 content[i][4] = od.getSettleaccounts().toString();
        }
        
      //创建HSSFWorkbook 
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
        	this.setResponseHeader(response, fileName);
        	OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
        }catch(Exception e){
        	e.getStackTrace();
        }
		
		
		
		
    }
	
}
